package com.asset.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.convert.converter.Converter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author 11725
 */
@Slf4j
public class DateConverter implements Converter<String, Date> {

    private static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
    private static final String SHORT_DATE_FORMAT = "yyyy-MM-dd";
    private static final String TIMESTAMP_FORMAT = "^\\d+$";

    private static final String NULL_VALUE = "null";

    @Override
    public Date convert(String value) {
        log.debug("日期转换：{}", value);

        if (value == null || "".equals(value.trim()) || NULL_VALUE.equalsIgnoreCase(value)) {
            return null;
        }

        value = value.trim();

        SimpleDateFormat formatter;
        if (value.contains(":")) {
            formatter = new SimpleDateFormat(DATE_FORMAT);
        } else {
            formatter = new SimpleDateFormat(SHORT_DATE_FORMAT);
        }

        try {
            return formatter.parse(value);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return null;
    }
}
